from django.shortcuts import render, redirect
from django.http import JsonResponse
from apps.sales_man.models import SalesMan
from apps.product.models import Product
from core.tools.encryption import md5
from apps.sales_man.models import Channel, ChannelProduct, ChannelMenus
from apps.order.models import PriceUpdate
from .admin_utils import channel_add_edit, paginator, admin_login
from .forms import LoginForm
from .models import ExtendSalesman, UserType
from .menus_tools import menus_permission


def login(request):
    login_form = LoginForm()
    if request.method == "POST":
        account = request.POST.get("username")
        password = request.POST.get("password")
        password = md5(md5(password))
        try:
            salesman = SalesMan.objects.get(account=account, password=password)
        except Exception as e:
            print(e)
            login_form.errors["message"] = "用户名或密码错误!"
            return render(request, "base/login.html", locals())
        if salesman.leader:
            login_form.errors["message"] = "没有登录后台的权限!"
            return render(request, "base/login.html", locals())
        else:
            request.session["admin_salesman"] = salesman
            return redirect("/admin/channel_price_list")
    else:
        return render(request, "base/login.html", locals())


def logout(request):
    try:
        del request.session["admin_salesman"]
    except Exception as e:
        pass
    url = '/admin/login'
    return redirect(url)


# -------------渠道管理start-------------
@admin_login()
@menus_permission()
def list_channel(request):
    name = request.GET.get("name")
    page = request.GET.get("page", 1)
    channels = Channel.objects.all()
    if name:
        channels = channels.filter_name(name)
    channels, page_dict = paginator.get_paging(channels, page=page)
    url_dict = paginator.make_url(request, page_dict)
    context = {"channels": channels, "page_dict": page_dict, "url_dict": url_dict}
    return render(request, "c2c_admin/channel/index.html", context)


@admin_login()
@menus_permission()
def add_channel(request):
    if request.method == "POST":
        data = channel_add_edit(request)
        try:
            account = data.get('account')
            check_menus = data.get('check_menus')
            salesman_qs = SalesMan.objects.filter(account=account)
            if salesman_qs.exists():
                content = {"status": 'error', "msg": "账号重复，请更换其他账号"}
                return JsonResponse(content)
            channels = Channel.objects.filter(tel=data.get("tel"), name=data.get("name"))
            if channels.exists():
                content = {"status": 'error', "msg": "请勿重复添加"}
            else:
                channel_obj = Channel.objects.create_channel(**data)  # 添加渠道
                products = data.get('products')
                for i in products:
                    # 添加产品
                    channel_product_obj = ChannelProduct.objects.create(
                        channel=channel_obj,
                        product_id=i,
                    )
                    # 添加价格
                    PriceUpdate.objects.create_price(channel_product_obj)
                sign = data.get('sign')
                if int(check_menus) != 1:
                    for i in sign:
                        ChannelMenus.objects.create(  # 添加渠道菜单
                            channel=channel_obj,
                            name=i
                        )
                # 添加业务员
                salesman_obj = SalesMan.objects.create_account(channel_obj, **data)
                # 添加渠道权限
                ExtendSalesman.objects.create(
                    sales=salesman_obj,
                    user_type=UserType.objects.get(account_type=2)
                )
                content = {"status": 'ok', "msg": "添加成功"}
        except Exception as e:
            print(e)
            content = {"status": 'error', "msg": "服务异常"}
        return JsonResponse(content)
    else:
        not_set = Product.objects.base_list
        no_set_menu = ChannelMenus.objects.base_menus
        return render(request, "c2c_admin/channel/add.html", locals())


@admin_login()
@menus_permission()
def edit_channel(request, channel_id):
    channel_obj = Channel.objects.get(id=channel_id)
    if request.method == "POST":
        data = channel_add_edit(request)
        try:
            # 更新渠道信息
            channel_obj.update_data(data)
            products = data.get("products")  # 用户想要绑定的数据
            # 更新渠道产品
            for i in products:
                channel_product_obj, created = ChannelProduct.objects.create_new_product(channel_obj, i)
                # 添加价格
                if created:
                    PriceUpdate.objects.create_price(channel_product_obj)
            # 将此渠道除了用户选择的产品外，其他产品更新为status=false
            difference_qs = ChannelProduct.objects.filter(channel=channel_obj).exclude(product_id__in=products)
            difference_qs.update(status=False)
            # 更新渠道在零号金融里看到的菜单
            check_menus = data.get("check_menus")
            sign = data.get("sign")
            if int(check_menus) != 1:
                ChannelMenus.objects.filter(channel=channel_obj).delete()
                for i in sign:
                    ChannelMenus.objects.create(
                        channel=channel_obj,
                        name=i
                    )
            content = {"status": 'ok', "msg": "修改成功"}
        except Exception as e:
            print(e)
            content = {"status": 'error', "msg": "服务异常"}
        return JsonResponse(content)
    else:
        not_set = Product.objects.difference_products(channel_obj)  # 未选择的产品
        seted = Product.objects.get_channel_products(channel_obj, status=True)  # 已选择的产品
        set_menu = ChannelMenus.objects.filter(channel=channel_obj)  # 渠道菜单已选择
        no_set_menu = ChannelMenus.objects.no_set_menus(channel_obj)
        return render(request, "c2c_admin/channel/add.html", locals())


# -------------渠道管理end-------------


# -------------渠道产品价格管理start-------------
@admin_login()
@menus_permission()
def channel_product_list(request, channel_id):
    channel_obj = Channel.objects.get(id=channel_id)
    product_name = request.GET.get("name")
    page = request.GET.get("page")
    products = ChannelProduct.objects.get_channel_products(channel_id, status=True)
    if product_name:
        products = products.filter(product__name__contains=product_name)
    products, page_dict = paginator.get_paging(products, page=page)
    url_dict = paginator.make_url(request, page_dict)
    context = {"products": products, "page_dict": page_dict, "url_dict": url_dict, "channel_id": channel_id,
               "channel_obj": channel_obj}
    return render(request, "c2c_admin/channel/products.html", context)


@admin_login()
@menus_permission()
def edit_channel_product(request, channel_product_id):
    channel_product_obj = ChannelProduct.objects.get(id=channel_product_id)
    channel_id = channel_product_obj.channel.id
    product_obj = channel_product_obj.product
    if request.method == "POST":
        sum_price = float(request.POST.get("sum_price"))
        update_time = request.POST.get("update_time")
        try:
            channel_product_obj.sum_price = sum_price
            channel_product_obj.update_time = update_time
            channel_product_obj.save()
            price_update_qs = PriceUpdate.objects.filter(channel_product=channel_product_obj)
            if price_update_qs.exists():
                base_price_record = price_update_qs.order_by("-id").first()
                PriceUpdate.objects.create_price(channel_product_obj, base_record=base_price_record,
                                                 update_time=update_time)
            else:
                PriceUpdate.objects.create_price(channel_product_obj, update_time=update_time)
            content = {"status": "ok", "msg": "修改成功"}
        except Exception as e:
            print(e)
            content = {"status": "error", "msg": "系统错误"}
        return JsonResponse(content)
    else:
        channel_product_obj = ChannelProduct.objects.get(id=channel_product_id)
        return render(request, "c2c_admin/channel/edit_price.html", locals())


@admin_login()
@menus_permission()
def add_channel_product(request, channel_id):
    channel_obj = Channel.objects.get(id=channel_id)
    if request.method == "POST":
        product = request.POST.get("product")
        product_obj = Product.objects.get(id=product)
        sum_price = request.POST.get("sum_price")
        sum_price = float(sum_price)
        update_time = request.POST.get("update_time")
        try:
            channel_product_obj = ChannelProduct.objects.create(
                channel=channel_obj,
                product_id=product,
                sum_price=sum_price,
            )
            PriceUpdate.objects.create_price(channel_product_obj, update_time=update_time)
            content = {"status": "ok", "msg": "添加成功"}
        except Exception as e:
            print(e)
            content = {"status": "error", "msg": "系统错误"}
        return JsonResponse(content)
    else:
        not_set = Product.objects.difference_products(channel_obj)
        return render(request, "c2c_admin/channel/edit_price.html", locals())


# -------------渠道产品价格管理end-------------


# -------------渠道操作价格start-------------
@admin_login()
@menus_permission()
def channel_add_price(request, channel_product):
    if request.method == "POST":
        reserved_b = float(request.POST.get("reserved_b"))
        level1 = float(request.POST.get("level1"))
        level2 = float(request.POST.get("level2"))
        level3 = float(request.POST.get("level3"))
        if reserved_b > 0.2:
            content = {"status": "error", "msg": "预留占比不能超过0.2"}
            return JsonResponse(content)
        sum_b = reserved_b + level1 + level2 + level3
        if not 1 >= sum_b > 0.99999:
            content = {"status": "error", "msg": "比例分配总和1"}
            return JsonResponse(content)
        try:
            PriceUpdate.objects.create(
                reserved_b=reserved_b,
                level1=level1,
                level2=level2,
                level3=level3,
                channel_product_id=channel_product
            )
            content = {"status": "ok", "msg": "添加成功"}
        except Exception as e:
            print(e)
            content = {"status": "error", "msg": "系统错误"}
        return JsonResponse(content)
    salesman = request.session.get("admin_salesman")
    products = ChannelProduct.objects.get(id=channel_product)
    return render(request, "c2c_admin/sn/add_price.html", locals())


@admin_login()
@menus_permission()
def channel_price_list(request):
    product_name = request.GET.get("name")
    page = request.GET.get("page")
    salesman = request.session["admin_salesman"]
    channel = salesman.channel
    if product_name:
        id_list = PriceUpdate.objects.get_price_list(channel, product_name=product_name)
    else:
        id_list = PriceUpdate.objects.get_price_list(channel)
    from .admin_utils import DjangoPaginator
    id_list, page_dict = DjangoPaginator().get_paging(id_list, page=page)
    url_dict = paginator.make_url(request, page_dict)
    qs = PriceUpdate.objects.filter(id__in=id_list)
    context = {"products": qs, "page_dict": page_dict, "url_dict": url_dict}
    return render(request, "c2c_admin/sn/price.html", context)

# -------------渠道操作价格end-------------
